<template>
  <AdVxeModal
    v-bind="$attrs"
    @register="register"
    :id="formIndex"
    :title="`${t('routes.system.identity.organization.title')} - ${FormModeEntityRef.Display}`"
    :help-message="`${t('common.form')}：${formIndex}`"
    :cancelText="t('common.cancelText')"
    :close-func="handleClose"
    :okText="FormModeEntityRef.OkBtnTitle"
    @ok="handleOk"
    @open-change="handleOpenChange"
    width="70%"
  >
    <a-row @contextmenu="handleContextMenu">
      <a-col :xs="24" :sm="24" :md="24" :lg="19" :xl="19" :xxl="19" :xxxl="19">
        <BasicForm @register="registerForm">
          <template #parentId="{ model, field }">
            <ApiTreeSelect
              v-model:value="model[field]"
              :treeData="parentTreeRef"
              labelField="Name"
              valueField="Id"
              childrenField="Items"
              :allowClear="true"
              :showSearch="true"
              treeNodeFilterProp="Name"
              :treeDefaultExpandAll="true"
            />
          </template>
        </BasicForm>
      </a-col>
      <a-col :xs="24" :sm="24" :md="24" :lg="5" :xl="5" :xxl="5" :xxxl="5">
        <div class="change-avatar">
          <!-- <div class="mb-2"> {{ t('routes.system.identity.organization.avatarTitle') }} </div> -->
          <img width="140" :src="avatarBase64Ref || uploadImg" />
          <Upload :showUploadList="false" :accept="avatarFormat" :beforeUpload="handleUploadLogo">
            <Button :disabled="uploadBtnDisabledRef">
              <Icon icon="feather:upload" />{{ t('component.upload.upload') }}
            </Button>
          </Upload>
        </div>
        <div class="change-avatar">
          <!-- <div class="mb-2"> {{ t('routes.system.identity.organization.signatureTitle') }} </div> -->
          <img width="200" :src="signatureBase64Ref || signatureImg" />
          <Upload
            :showUploadList="false"
            :accept="signatureFormat"
            :beforeUpload="handleUploadSignature"
          >
            <Button :disabled="uploadBtnDisabledRef">
              <Icon icon="feather:upload" />{{ t('component.upload.upload') }}
            </Button>
          </Upload>
        </div>
      </a-col>
    </a-row>
  </AdVxeModal>

  <PrintTemplateModal @register="templateModalRegister" v-bind="templateModalProps" />
</template>

<script lang="ts" setup>
  import type { PropType } from 'vue';
  import { h, ref } from 'vue';
  import { Button, Select, Upload, Row, Col } from 'ant-design-vue';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useContextMenu } from '@/hooks/web/useContextMenu';
  import { destroyContextMenu } from '@/components/ContextMenu';

  import uploadImg from '@/assets/images/upload_file.png';
  import signatureImg from '@/assets/images/signature_solid.png';

  import { PrintTemplateModal, useAdPrint } from '@/components/AdPrint';
  import { AdVxeModal, useModalInner } from '@/components/AdVxeModal';
  import { BasicForm, useForm, ApiTreeSelect } from '@/components/Form';
  import { FormSchema } from '@/components/Table';
  import Icon from '@/components/Icon/Icon.vue';

  import { useI18n } from '@/hooks/web/useI18n';
  import { isFunction } from '@/utils/is';
  import { getBase64 } from '@/utils/common';

  import { FormModeEnum, FormModeEntity } from '@/enums/formEnum';

  import { AjaxResult } from '#/request';
  import { OrganizationInputDto } from '@/api/identity/admin/organization/model';
  import { OrganizationTreeNode } from '@/api/identity/model';
  import {
    getOrganizations,
    getTreeNodesExclude,
    createOrganizations,
    updateOrganizations,
    deleteOrganizations,
  } from '@/api/identity/admin/organization';
  import { getOrganizationTypeEnumSchema } from '@/enums/organizationTypeEnum';

  const ARow = Row;
  const ACol = Col;

  defineOptions({ name: 'OrganizationDetailModal' });
  const props = defineProps({
    /** 关闭回调，返回true关闭窗体 */
    closeFunc: {
      type: Function as PropType<
        (formMode: FormModeEnum, record: OrganizationInputDto) => Promise<boolean>
      >,
      default: null,
    },
    /** 提交前回调，返回false不执行内置提交逻辑，返回true执行内置提交逻辑 */
    beforeSubmitFunc: {
      type: Function as PropType<
        (formMode: FormModeEnum, record: OrganizationInputDto) => Promise<boolean>
      >,
      default: null,
    },
    /** 提交后回调，返回true关闭窗体 */
    afterSubmitFunc: {
      type: Function as PropType<
        (
          formMode: FormModeEnum,
          result: AjaxResult | null,
          record: OrganizationInputDto,
        ) => Promise<boolean>
      >,
      default: null,
    },
  });

  const { t } = useI18n();
  const { createMessage } = useMessage();
  const [createContextMenu] = useContextMenu();
  const formIndex = 'identity_organization_detail';
  const keyField = 'Id';

  const uploadBtnDisabledRef = ref(false);
  const avatarFormat = '.jpg,.jpeg,.png,.bmp,.ico,.gif';
  const avatarBase64Ref = ref<string | undefined>('');
  const signatureFormat = '.jpg,.jpeg,.png,.bmp';
  const signatureBase64Ref = ref<string | undefined>('');
  const parentTreeRef = ref<OrganizationTreeNode[]>([]);
  const formModeRef = ref<FormModeEnum>(FormModeEnum.Ok);
  const FormModeEntityRef = ref<FormModeEntity>(new FormModeEntity(formModeRef.value));

  //#region "加载状态"
  const loadingRef = ref(false);
  /** 开启加载状态 */
  function openLoading() {
    changeLoading(true);
    setModalProps({ okLoading: true, cancelLoading: true });
    loadingRef.value = true;
  }
  /** 关闭加载状态 */
  function closeLoading() {
    changeLoading(false);
    setModalProps({ okLoading: false, cancelLoading: false });
    loadingRef.value = false;
  }
  //#endregion
  //#region 定义高级打印
  const { printContextMenus, templateModalRegister, templateModalProps } = useAdPrint({
    formIndex: formIndex,
    keyField: keyField,
    getFormData: () => getFieldsValue(),
  });
  /** 处理上下文菜单(右键菜单) */
  function handleContextMenu(e: MouseEvent) {
    const element = document.elementFromPoint(e.clientX, e.clientY) as Element;
    const cursor = document.defaultView?.getComputedStyle(element, null).cursor;
    // console.log('handleContextMenu', {
    //   cursor: cursor,
    // });

    let items: any[] = [];
    switch (FormModeEntityRef.value.FormMode) {
      case FormModeEnum.Ok:
      case FormModeEnum.Edit:
      case FormModeEnum.ReadOnly:
        if (!cursor || cursor === 'default' || cursor === 'auto') {
          items = [...printContextMenus];
        }
        break;
    }
    if (items && items?.length > 0) {
      createContextMenu({
        event: e,
        styles: {
          border: '1px solid #eee',
          'border-radius': '2px',
          'box-shadow': '3px 3px 3px rgb(0 0 0 / 15%)',
        },
        items: [...items],
      });
    }
  }
  //#endregion

  const schemas: FormSchema[] = [
    {
      field: 'Id',
      helpMessage: `${t('common.field')}：${'Id'}`,
      component: 'Input',
      label: t('entity.idTitle'),
      componentProps: { disabled: true },
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'Code',
      helpMessage: `${t('common.field')}：${'Code'}`,
      component: 'Input',
      label: t('entity.codeTitle'),
      required: true,
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'Name',
      helpMessage: `${t('common.field')}：${'Name'}`,
      component: 'Input',
      label: t('routes.system.identity.organization.nameTitle'),
      required: true,
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'NameFrgn',
      helpMessage: `${t('common.field')}：${'NameFrgn'}`,
      component: 'Input',
      label: t('routes.system.identity.organization.frgnTitle'),
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'Address',
      helpMessage: `${t('common.field')}：${'Address'}`,
      component: 'InputTextArea',
      label: t('routes.system.identity.organization.addressTitle'),
      // componentProps: { showCount: false, autosize: { minRows: 2, maxRows: 6 } },
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'AddressFrgn',
      helpMessage: `${t('common.field')}：${'AddressFrgn'}`,
      component: 'InputTextArea',
      label: t('routes.system.identity.organization.frgnTitle'),
      // componentProps: { showCount: false, autosize: { minRows: 2, maxRows: 6 } },
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'PrintHeader',
      helpMessage: `${t('common.field')}：${'PrintHeader'}`,
      component: 'Input',
      label: t('routes.system.identity.organization.printHeaderTitle'),
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'PrintHeaderFrgn',
      helpMessage: `${t('common.field')}：${'PrintHeaderFrgn'}`,
      component: 'Input',
      label: t('routes.system.identity.organization.frgnTitle'),
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'ReptName',
      helpMessage: `${t('common.field')}：${'ReptName'}`,
      component: 'Input',
      label: t('routes.system.identity.organization.reptNameTitle'),
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'ReptNameFrgn',
      helpMessage: `${t('common.field')}：${'ReptNameFrgn'}`,
      component: 'Input',
      label: t('routes.system.identity.organization.frgnTitle'),
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'Type',
      helpMessage: `${t('common.field')}：${'Type'}`,
      component: 'Select',
      label: t('routes.system.identity.organization.typeTitle'),
      required: true,
      render: ({ model, field }) => {
        return h(Select, {
          options: [...getOrganizationTypeEnumSchema()],
          showSearch: true,
          optionFilterProp: 'label',
          value: model[field],
          onChange: (e: any) => {
            model[field] = e;
            switch (e) {
              case 1:
                model['EnableLogin'] = false;
                break;
              case 2:
                model['EnableLogin'] = true;
                break;
              case 3:
                model['EnableLogin'] = false;
                break;
            }
            // console.log('OrgTypeChange_model', model);
            // console.log('OrgTypeChange_field', field);
            // console.log('OrgTypeChange_e', e);
          },
        });
      },
      dynamicDisabled: ({ values }) => {
        return !!values.IsSystem;
      },
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'GLNumber',
      helpMessage: `${t('common.field')}：${'GLNumber'}`,
      component: 'Input',
      label: t('common.glNumberText'),
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'Email',
      helpMessage: `${t('common.field')}：${'Email'}`,
      component: 'Input',
      label: t('common.emailText'),
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'PhoneNumber',
      helpMessage: `${t('common.field')}：${'PhoneNumber'}`,
      component: 'Input',
      label: t('common.phoneNumberText'),
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'TelNumber',
      helpMessage: `${t('common.field')}：${'TelNumber'}`,
      component: 'Input',
      label: t('common.telNumberText'),
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'FaxNumber',
      helpMessage: `${t('common.field')}：${'FaxNumber'}`,
      component: 'Input',
      label: t('common.faxNumberText'),
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'Description',
      helpMessage: `${t('common.field')}：${'Description'}`,
      component: 'Input',
      label: t('routes.system.identity.organization.descriptionTitle'),
      colProps: {
        // span: 24,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 24, // ≥1200px
        xxl: 24, // ≥1600px
        // xxxl: 24, // ≥2000px 3.0
      },
    },
    {
      field: 'Remark',
      helpMessage: `${t('common.field')}：${'Remark'}`,
      component: 'InputTextArea',
      label: t('routes.system.identity.organization.remarkTitle'),
      componentProps: {
        showCount: true,
        // autosize: { minRows: 2, maxRows: 6 },
      },
      colProps: {
        // span: 24,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 24, // ≥1200px
        xxl: 24, // ≥1600px
        // xxxl: 24, // ≥2000px 3.0
      },
    },
    { field: 'divider-basic', component: 'Divider', label: '', colProps: { span: 24 } },
    {
      field: 'ParentId',
      helpMessage: `${t('common.field')}：${'ParentId'}`,
      // component: 'ApiTreeSelect',
      label: t('routes.system.identity.organization.parentIdTitle'),
      slot: 'parentId',
      dynamicDisabled: ({ values }) => {
        return !!values.IsSystem;
      },
      colProps: {
        // span: 16,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 16, // ≥1200px
        xxl: 16, // ≥1600px
        // xxxl: 16, // ≥2000px 3.0
      },
    },
    {
      field: 'OrderNumber',
      helpMessage: `${t('common.field')}：${'OrderNumber'}`,
      component: 'InputNumber',
      label: t('routes.system.identity.organization.orderNumberTitle'),
      componentProps: {
        style: { width: '100%' },
      },
      colProps: {
        // span: 8,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 12, // ≥768px
        lg: 12, // ≥992px
        xl: 8, // ≥1200px
        xxl: 8, // ≥1600px
        // xxxl: 8, // ≥2000px 3.0
      },
    },
    {
      field: 'TreePathString',
      helpMessage: `${t('common.field')}：${'TreePathString'}`,
      component: 'InputTextArea',
      label: t('routes.system.identity.organization.treePathStringTitle'),
      componentProps: {
        disabled: true,
        showCount: false,
        // autosize: { minRows: 2, maxRows: 6 },
      },
      colProps: {
        // span: 24,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 24, // ≥1200px
        xxl: 24, // ≥1600px
        // xxxl: 24, // ≥2000px 3.0
      },
    },
    {
      field: 'Level',
      helpMessage: `${t('common.field')}：${'Level'}`,
      component: 'InputNumber',
      label: t('routes.system.identity.organization.levelTitle'),
      componentProps: {
        disabled: true,
        style: { width: '100%' },
      },
      colProps: {
        // span: 24,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 24, // ≥1200px
        xxl: 24, // ≥1600px
        // xxxl: 24, // ≥2000px 3.0
      },
    },
    {
      field: 'EnableLogin',
      helpMessage: `${t('common.field')}：${'EnableLogin'}`,
      component: 'Switch',
      label: t('routes.system.identity.organization.enableLoginTitle'),
      dynamicDisabled: ({ values }) => {
        return !!values.IsSystem;
      },
      colProps: {
        // span: 6,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 12, // ≥768px
        lg: 12, // ≥992px
        xl: 6, // ≥1200px
        xxl: 6, // ≥1600px
        // xxxl: 6, // ≥2000px 3.0
      },
    },
    {
      field: 'IsLocked',
      helpMessage: `${t('common.field')}：${'IsLocked'}`,
      component: 'Switch',
      label: t('entity.lockable.isLockedTitle'),
      colProps: {
        // span: 6,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 12, // ≥768px
        lg: 12, // ≥992px
        xl: 6, // ≥1200px
        xxl: 6, // ≥1600px
        // xxxl: 6, // ≥2000px 3.0
      },
    },
    {
      field: 'IsDefault',
      helpMessage: `${t('common.field')}：${'IsDefault'}`,
      component: 'Switch',
      label: t('routes.system.identity.organization.isDefaultTitle'),
      colProps: {
        // span: 6,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 12, // ≥768px
        lg: 12, // ≥992px
        xl: 6, // ≥1200px
        xxl: 6, // ≥1600px
        // xxxl: 6, // ≥2000px 3.0
      },
    },
    {
      field: 'IsSystem',
      helpMessage: `${t('common.field')}：${'IsSystem'}`,
      component: 'Switch',
      label: t('routes.system.identity.organization.isSystemTitle'),
      componentProps: { disabled: true },
      colProps: {
        // span: 6,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 12, // ≥768px
        lg: 12, // ≥992px
        xl: 6, // ≥1200px
        xxl: 6, // ≥1600px
        // xxxl: 6, // ≥2000px 3.0
      },
    },
    {
      field: 'CreatedTime',
      helpMessage: `${t('common.field')}：${'CreatedTime'}`,
      component: 'DatePicker',
      label: t('entity.creationAudited.createdTimeTitle'),
      componentProps: {
        disabled: true,
        showTime: true,
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        style: { width: '100%' },
      },
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'UpdatedTime',
      helpMessage: `${t('common.field')}：${'UpdatedTime'}`,
      component: 'DatePicker',
      label: t('entity.updateAudited.updatedTimeTitle'),
      componentProps: {
        disabled: true,
        showTime: true,
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        style: { width: '100%' },
      },
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
  ];

  const [registerForm, { resetFields, getFieldsValue, setFieldsValue, validate }] = useForm({
    labelWidth: 160,
    schemas: schemas,
    showActionButtonGroup: false,
    compact: true,
  });

  const [register, { setModalProps, closeModal, changeLoading }] = useModalInner(async (data) => {
    resetFields();
    changeLoading(true);
    try {
      avatarBase64Ref.value = undefined;
      if (data.formMode) {
        formModeRef.value = data.formMode as FormModeEnum;
        FormModeEntityRef.value = new FormModeEntity(formModeRef.value);

        uploadBtnDisabledRef.value =
          FormModeEntityRef.value.FormMode !== FormModeEnum.Add &&
          FormModeEntityRef.value.FormMode !== FormModeEnum.Edit;
      }
      if (data.record) {
        await setFieldsValue({
          ...data.record,
        });
        avatarBase64Ref.value = data.record?.Avatar;
        signatureBase64Ref.value = data.record?.Signature;
        if (data.record?.Id) {
          const dtos = await getOrganizations([data.record.Id]);
          if (dtos?.length > 0) {
            await setFieldsValue({
              ...dtos[0],
            });
            avatarBase64Ref.value = dtos[0]?.Avatar;
            signatureBase64Ref.value = dtos[0]?.Signature;
          }
        }
      }
      parentTreeRef.value = await getTreeNodesExclude(data.record?.Id);
      // console.log('parentTree', parentTreeRef.value);
    } finally {
      changeLoading(false);
    }
  });

  /** 处理上传Logo */
  const handleUploadLogo = (file: File) => {
    try {
      openLoading();

      const isJpgOrPng =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/bmp' ||
        file.type === 'image/gif' ||
        file.type === 'image/x-icon';
      if (!isJpgOrPng) {
        createMessage.error(t('component.upload.acceptUpload', [avatarFormat]));
        return isJpgOrPng;
      }
      const isLt2M = file.size / 1024 / 1024 < 1;
      if (!isLt2M) {
        createMessage.error(t('component.upload.maxSize', '1'));
        return isLt2M;
      }
      getBase64(file, (base64Url: string) => {
        avatarBase64Ref.value = base64Url;
        // await setFieldsValue({
        //   Avatar: base64Url,
        // });
      });
    } finally {
      closeLoading();
    }
    return false;
  };
  /** 处理上传签名 */
  const handleUploadSignature = (file: File) => {
    try {
      openLoading();

      const isJpgOrPng =
        file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/bmp';
      if (!isJpgOrPng) {
        createMessage.error(t('component.upload.acceptUpload', [signatureFormat]));
        return isJpgOrPng;
      }
      const isLt2M = file.size / 1024 / 1024 < 1;
      if (!isLt2M) {
        createMessage.error(t('component.upload.maxSize', '1'));
        return isLt2M;
      }
      getBase64(file, (base64Url: string) => {
        signatureBase64Ref.value = base64Url;
        // await setFieldsValue({
        //   Signature: base64Url,
        // });
      });
    } finally {
      closeLoading();
    }
    return false;
  };

  /** 获取组织机构信息输入DTO */
  function getInputDto(): OrganizationInputDto {
    const record = getFieldsValue() as OrganizationInputDto;
    record.Avatar = avatarBase64Ref.value;
    record.Signature = signatureBase64Ref.value;
    return record;
  }

  /** 处理关闭按钮 */
  async function handleClose() {
    openLoading();

    const { closeFunc } = props;
    try {
      if (closeFunc && isFunction(closeFunc)) {
        const inputDto = getInputDto();
        const result = await closeFunc(FormModeEntityRef.value.FormMode, inputDto);
        return result;
      }
    } finally {
      closeLoading();
    }
    return true;
  }
  /** 处理确定按钮 */
  async function handleOk() {
    const data = await validate();
    if (!data) return;
    //console.log(data);

    openLoading();

    const { beforeSubmitFunc, afterSubmitFunc } = props;
    try {
      const inputDto = getInputDto();
      let innerSubmit = true;
      let innerCloseModal = true;
      if (beforeSubmitFunc && isFunction(beforeSubmitFunc)) {
        innerSubmit = await beforeSubmitFunc(FormModeEntityRef.value.FormMode, inputDto);
      }
      let result: AjaxResult | null = null;
      if (innerSubmit) {
        switch (FormModeEntityRef.value.FormMode) {
          case FormModeEnum.Add:
            result = await createOrganizations([inputDto]);
            break;
          case FormModeEnum.Edit:
            result = await updateOrganizations([inputDto]);
            break;
          case FormModeEnum.Delete:
            result = await deleteOrganizations([inputDto.Id]);
            break;
        }
      }
      if (afterSubmitFunc && isFunction(afterSubmitFunc)) {
        innerCloseModal = await afterSubmitFunc(FormModeEntityRef.value.FormMode, result, inputDto);
      }
      if (innerCloseModal) {
        closeModal();
      }
    } finally {
      closeLoading();
    }
  }
  /** 打开或者关闭触发 */
  function handleOpenChange(open: boolean) {
    if (!open) {
      destroyContextMenu();
    }
  }
</script>

<style lang="less" scoped>
  .change-avatar {
    margin: 0 auto;
    margin-bottom: 15px;
    text-align: center;

    img {
      display: block;
      margin: 0 auto;
      margin-bottom: 15px;
      text-align: center;
      // border-radius: 30%;
    }
  }

  .context-menu {
    z-index: 8888 !important;
  }
</style>
